const express = require("express");
const cors = require("cors");
const app = express();

// 导入路由
const userController = require("./controller/UserController");
const staffController = require("./controller/StaffController");
const staffInfoController = require("./controller/StaffInfoController");
const allowanceRoutes = require("./routes/allowance");
const salaryController = require("./controller/SalaryController");

// 测试数据库连接
const { testConnection } = require("./database/db");
testConnection();

// 中间件
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// 注册路由
app.use("/users", userController);
app.use("/staff", staffController);
app.use("/staffInfo", staffInfoController);
app.use("/allowance", allowanceRoutes);
app.use("/salary", salaryController);

// 404 处理
app.use((req, res, next) => {
    res.status(404).json({
        code: 404,
        msg: '请求的资源不存在'
    });
});

// 错误处理中间件
app.use((err, req, res, next) => {
    console.error('服务器错误:', err);
    res.status(500).json({
        code: 500,
        msg: '服务器内部错误: ' + (err.message || '未知错误')
    });
});

// 处理未捕获的异常
process.on('uncaughtException', (err) => {
    console.error('未捕获的异常:', err);
});

// 处理未处理的Promise拒绝
process.on('unhandledRejection', (reason, promise) => {
    console.error('未处理的Promise拒绝:', reason);
});

const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
    console.log(`服务器运行在端口 ${PORT}`);
});

module.exports = app;